﻿using Microsoft.Extensions.Caching.Distributed;
using StackExchange.Profiling.Internal;
using static OpenAdmin.Core.Consts.CachingConsts;

namespace OpenAdmin.Application.Redis;

/// <summary>
/// 
/// </summary>
public static class CachingExtensions
{
    /// <summary>
    /// 获取或添加
    /// </summary>
    /// <typeparam name="TCacheItem"></typeparam>
    /// <param name="cache"></param>
    /// <param name="key"></param>
    /// <param name="factory"></param>
    /// <param name="minutes"></param>
    /// <returns></returns>
    public static async Task<TCacheItem> GetOrAddAsync<TCacheItem>(this IDistributedCache cache, string key, Func<Task<TCacheItem>> factory, int minutes)
        where TCacheItem : class
    {
        TCacheItem cacheItem;

        var result = await cache.GetStringAsync(key);
        if (string.IsNullOrEmpty(result))
        {
            cacheItem = await factory.Invoke();

            var options = new DistributedCacheEntryOptions();
            if (minutes != CacheStrategy.NEVER)
            {
                options.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutes);
            }

            await cache.SetStringAsync(key, cacheItem.ToJson(), options);
        }
        else
        {
            cacheItem = Newtonsoft.Json.JsonConvert.DeserializeObject<TCacheItem>(result);
        }

        return cacheItem;
    }
}
